package com.fubon.wloan.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.TypeReference;
import com.couchbase.client.java.error.DocumentAlreadyExistsException;
import com.fubon.wloan.constant.RetCode;
import com.fubon.wloan.pojo.Msg;
import com.fubon.wloan.pojo.Resp;
import com.fubon.wloan.pojo.Trans;
import com.fubon.wloan.repository.TransRepository;
import com.fubon.wloan.util.CryptoUtil;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import reactor.core.publisher.Mono;

@Service
public class TransServiceImpl implements TransService {

    @Autowired
    TransRepository transRepository;
    
    private <T> Mono<T> alreadyExists(String id) {
        return Mono.error(new DocumentAlreadyExistsException("Person with id " + id + " already exists"));
    }
    
    @Override
    public  <T,V> Msg<T,V> parseByType(Trans msg){
        Trans trans = CryptoUtil.decode(msg);

        Msg<T,V> res = JSON.parseObject(trans.getData(), new TypeReference<Msg<T,V>>() {});
        return res;
    }

    @Override
    public  <T> Trans encodeByType(T t){
        return CryptoUtil.encode(Trans.builder().icode("xxxx").data(JSON.toJSONString(t)).build());
    }

    @Override
    public Mono<Trans> SaveCreditReqToCouchbase(Msg msg) {
        String reqSn = "";
        Resp resp;
        try {

            Trans trans  = Trans.builder().icode("xxxx").data(JSON.toJSONString(msg)).build();
            reqSn = msg.getBody().getReqSn();
            trans.setId(reqSn);
            transRepository.existsById(trans.getId()).flatMap(exists-> exists ? alreadyExists(trans.getId()) : transRepository.save(trans)).subscribe();

            resp = new Resp(reqSn, RetCode.E0000);
            
        } catch (JSONException js) {
            resp = new Resp(reqSn, RetCode.E1000);

        } catch(DocumentAlreadyExistsException dc){
            resp = new Resp(reqSn, RetCode.E1001);
        } catch (Exception e) {
            e.printStackTrace();
            resp = new Resp(reqSn, RetCode.F1000);

        }
        System.out.println(JSON.toJSONString(resp));
        return Mono.just(encodeByType(resp));
    }

    @Override
    public Mono<Trans> SaveConsumeReqToCouchbase(Msg trans) {
        // TODO Auto-generated method stub
        return null;
    }


    
}